package de.pipeGame.itemStack;

import de.pipeGame.R;
import EventSourcing.DragComponent;
import android.content.ClipData;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class ItemStack implements DragComponent{
	ViewGroup viewGroup;
	int itemsLeft;
	ImageView image;
	TextView text; 
	int type; 
	
	ItemStack(ViewGroup viewGroup, int _type, int itemsLeft){
		this.viewGroup = viewGroup;
		this.itemsLeft=itemsLeft;
		this.type = _type;
		
		image = (ImageView)viewGroup.findViewById(R.id.image);
		text = (TextView) viewGroup.findViewById(R.id.text);
		
		image.setOnTouchListener(new StartDragListener());
	}
	
	private class StartDragListener implements OnTouchListener{
		public boolean onTouch(View view, MotionEvent motionEvent) {
	        if ((!isEmpty())&&(motionEvent.getAction() == MotionEvent.ACTION_DOWN)) {
	            ClipData clipData = ClipData.newPlainText("id", ""+type);
	            View.DragShadowBuilder dsb = new View.DragShadowBuilder(view);
	            view.startDrag(clipData, dsb, view, 0);
	            return true;
	        } else {
	            return false;
	        }
	    }
	}
	
	private void updateText(){
		text.setText(""+itemsLeft+" x");
		text.invalidate();
	}
	public void decreaseItems(){
		itemsLeft --;
		updateText();
		
		if (isEmpty()){
			text.setTextColor(text.getTextColors().withAlpha(100));

			image.setAlpha(100);
		}
	}
	
	public void increaseItems(){
		
		if (isEmpty()){
			text.setTextColor(text.getTextColors().withAlpha(255));
			image.setAlpha(255);
		}
		itemsLeft ++;
		updateText();
	}

	public boolean isEmpty(){
		return itemsLeft <= 0;
	}


	public View getImage() {
		return image;
	}
	
	public void performDragSourceEvent() {
		decreaseItems();
		
	}

	public void performDragTargetEvent(int dragItem) {
		increaseItems();
		
	}
}
